package com.tube.fiddles.dao.impl;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import com.tube.fiddles.dao.MenuDao;
import com.tube.fiddles.domain.Menu;
import com.tube.fiddles.domain.Menu_;
import com.tube.fiddles.support.dao.GenericDao;

@Repository("menuDao")
public class MenuDaoImpl extends GenericDao implements MenuDao {

    @Override
    public void save(Menu menu) {
        if (menu.isIdSet()) {
            this.merge(menu);
        } else {
            this.persist(menu);
        }
    }
    
    @Override
    public int count(Menu menu) {
        boolean distinct = false;
        CriteriaBuilder builder = this.getCriteriaBuilder();
        CriteriaQuery<Long> countQuery = builder.createQuery(Long.class);
        Root<Menu> root = countQuery.from(Menu.class);
        
        Predicate condition = builder.like(root.get(Menu_.menuName), "%" + menu.getMenuName() + "%");
        
        if (distinct) {
            countQuery.select(builder.countDistinct(root));
        } else {
            countQuery.select(builder.count(root));
        }
        countQuery.where(condition);
        
        TypedQuery<Long> typedQuery = createQuery(countQuery);
        Long count = typedQuery.getSingleResult();

        if (count != null) {
            return count.intValue();
        } else {
            return 0;
        }
    }
    
    /*public Account findByEmailByCriteria(String email) {
        CriteriaBuilder criteriaBuilder = this.getEntityManager().getCriteriaBuilder();
        CriteriaQuery<Account> criteriaQuery = criteriaBuilder.createQuery(Account.class);
        Root<Account> root = criteriaQuery.from(Account.class);
        
        Predicate condition = criteriaBuilder.equal(root.get(Account_.email), email);
        criteriaQuery.where(condition);
        
        root.<Address>fetch(Account_.address);
        
        criteriaQuery.orderBy(criteriaBuilder.asc(root.get(Account_.creationDate)));
        
        TypedQuery<Account> typedQuery = getEntityManager().createQuery(criteriaQuery);
        typedQuery.setMaxResults(1);
        Account account = typedQuery.getSingleResult();
        return account;
    }
*/
}
